// 这里提供对 jsBridge 对象的扩展

const doc = document

// 发送一个 domevent
// 参数务必以 json 方式传递
// window.TenvideoJSBridge.callEvent('event-name', '{"a":1}')
function callEvent(name, json) {
	var evt = doc.createEvent('Events')
	evt.initEvent(name)
	if (typeof json === 'string') {
		try {
			json = JSON.parse(json)
		} catch (err) {}
	}
	evt.args = json
	doc.dispatchEvent(evt)
}

function attachMethod (name) {
	let bridge = window[name]
	if (bridge && !bridge.callEvent) {
		bridge.callEvent = callEvent
	}
}

function initJsBridge (name) {
	attachMethod('WebViewJavascriptBridge')
	attachMethod('TenvideoJSBridge')
}

document.addEventListener('onTenvideoJSBridgeReady', initJsBridge, false)
initJsBridge()

export default initJsBridge
